package com.paas.form.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.paas.common.auth.service.IPermissionService;
import com.paas.common.core.encryp.AESUtil;
import com.paas.common.model.DataBaseEntity;
import com.paas.common.util.AppUtil;
import com.paas.common.util.BeanUtil;
import com.paas.common.util.StringUtil;
import com.paas.common.web.SystemConst;
import com.paas.db.common.element.conf.etl.EtlConf;
import com.paas.etlx.core.etl.EtlPluginExecutor;
import com.paas.etlx.core.util.UuidUtil;
import com.paas.form.entity.*;
import com.paas.form.enums.RunStateEnums;
import com.paas.form.handler.util.FormJobHandlerUtil;
import com.paas.form.service.*;
import com.paas.plus.tool.common.Configuration;
import com.paas.plus.tool.form.model.View;
import com.paas.plus.tool.form.server.FormService;
import com.paas.plus.tool.inteface.model.*;
import com.paas.plus.tool.inteface.model.enums.InterfaceTypeEnums;
import com.paas.plus.tool.inteface.server.IInterfaceService;
import com.paas.plus.tool.realTimeDistributed.model.FiledMappingTable;
import com.paas.plus.tool.realTimeDistributed.model.RealTimeDistributeConfig;
import com.paas.plus.tool.realTimeDistributed.model.RealTimeDistributeInterfaceConfig;
import com.paas.plus.tool.realTimeDistributed.model.RealTimeDistributeTableConfig;
import com.paas.scheduler.exception.SchedulerException;
import com.paas.scheduler.model.JobInstance;
import com.paas.scheduler.spi.JobHandler;
import com.paas.tool.feign.service.IMdmToolsRealtimeDistributionService;
import com.publics.feign.service.IUcDataBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
public class EtlTaskJobHandler implements JobHandler {

    private IMdmToolsRealtimeDistributionService realtimeDistributionService;

    private IUcDataBaseService dataBaseService;

    private IFormTaskService formTaskService;

    private IFormModelService formModelService;

    private IFormModelParamsService formModelParamsService;

    private IFormTaskParamsService formTaskParamsService;

    private IFormTaskMapperService formTaskMapperService;

    private IFormTaskLogService formTaskLogService;

    private IInterfaceService interfaceService;

    private Environment environment;

    private FormService formService;

    private String appCode;

    private String publicsKey;

    private JSONObject readerObj;

    private String executeSql;

    private View view;

    private String  thirdPartyToken;

    private RealTimeDistributeConfig realTimeDistributeConfig;

    private JobInstance jobInstance;

    private IFormTaskEtlLogService etlLogService;

    private JSONObject viewWriterObj;

    private int failCount = 0;
    private int successCount = 0;
    private int apiFailCount = 0;
    private int apiSuccessCount=0;


    private String getThirdPartyToken(String appCode,String publicsKey){
        IPermissionService permissionService = (IPermissionService) AppUtil.getBean(IPermissionService.class);
        log.info("mdm开始获取token");
        // 调用第三方应用获取令牌接口
        String token = permissionService.createThirdAppToken(appCode, publicsKey);
        log.info("mdm获取token成功：{}", token);
        return token;
    }


    @Override
    public String getType() {
        return "ETL_MDM_TASK";
    }

    @Override
    public void init(JobInstance jobInstance) {
        initService();
        initParams(jobInstance);
    }

    private void initParams(JobInstance jobInstance) {
        this.jobInstance = jobInstance;
        appCode = environment.getProperty("paas.token.thirdParty.appCode");
        publicsKey = environment.getProperty("paas.token.thirdParty.publicsKey");
        String thirdPartyToken = getThirdPartyToken(appCode, publicsKey);
        FormTaskEntity formTaskEntity = formTaskService.getById(jobInstance.getBusId());
        FormModelEntity modelEntity = formModelService.getById(formTaskEntity.getModelId());

        DataBaseEntity dataBaseEntity = dataBaseService.asyncQueryById(modelEntity.getDatabaseId(), thirdPartyToken);

        realTimeDistributeConfig = realtimeDistributionService.getDistributionConfiguration(formTaskEntity.getViewId(), "2",thirdPartyToken);

        Map<String, Object> resultMap;
        List<Map<String, Object>> sqlValueList = null;
        Map<String, String> columnMap = null;
        Map<String, FormModelParamsEntity> tempFormModelMap = new HashMap<>();

        FormModelParamsEntity formModelParamsEntity = new FormModelParamsEntity();
        //查询规则模型params
        formModelParamsEntity.setModelId(modelEntity.getId());
        List<FormModelParamsEntity> list = formModelParamsService.getList(formModelParamsEntity);
        tempFormModelMap = list.stream().collect(Collectors.toMap(FormModelParamsEntity::getId,item->item));

        FormTaskParamsEntity formTaskParamsEntity = new FormTaskParamsEntity();
        formTaskParamsEntity.setTaskId(formTaskEntity.getId());
        List<FormTaskParamsEntity> formTaskParamsList = formTaskParamsService.getList(formTaskParamsEntity);
        if (formTaskParamsList.size()>0){
            resultMap = FormJobHandlerUtil.parseParams(formTaskParamsList, tempFormModelMap);
            sqlValueList = (List<Map<String, Object>>) resultMap.get("params");
            columnMap= (Map<String, String>) resultMap.get("column");
        }

        //获取对应字段,对应的字段属性
        if (BeanUtil.isNotEmpty(sqlValueList) && BeanUtil.isNotEmpty(columnMap)){
            for (Map<String, Object> map : sqlValueList) {
                Iterator<Map.Entry<String, String>> iterator = columnMap.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    if (map.containsKey(next.getKey())){
                        map.put("tempType",next.getValue());
                        columnMap.remove(next.getKey());
                        break;
                    }
                }
            }
        }

        executeSql = FormJobHandlerUtil.formatSql(modelEntity.getExcelSql(),sqlValueList);


        FormTaskMapperEntity formTaskMapperEntity = new FormTaskMapperEntity();
        formTaskMapperEntity.setTaskId(formTaskEntity.getId());
        List<FormTaskMapperEntity> formTaskMapperList = formTaskMapperService.getList(formTaskMapperEntity);
        List<String> sourceColumn = new ArrayList<>();
        List<String> targetColumn = new ArrayList<>();
        if (BeanUtil.isEmpty(readerObj)){
            readerObj = new JSONObject();
        }
        readerObj.put("name",dataBaseEntity.getDbType()+"reader");
        StringBuilder sourceColumnBuffer = new StringBuilder();
        for (FormTaskMapperEntity taskMapperEntity : formTaskMapperList) {
            sourceColumn.add(taskMapperEntity.getSourceCloumn());
            if (StringUtil.isNullOrEmpty(sourceColumnBuffer.toString())){
                sourceColumnBuffer.append(taskMapperEntity.getSourceCloumn());
            }else {
                sourceColumnBuffer.append(",").append(taskMapperEntity.getSourceCloumn());
            }
            targetColumn.add(taskMapperEntity.getTargetCloumn());
        }
        JSONObject readerParameter = new JSONObject();
        JSONObject readerConnectionObj = new JSONObject();
        JSONArray array = new JSONArray();
        String sql = "select "+sourceColumnBuffer.toString()+ " from  (" + executeSql +") a";
        readerConnectionObj.put("querySql",sql);
        array.add(readerConnectionObj);
        readerParameter.put("jdbcUrl",dataBaseEntity.getJdbcUrl());
        readerParameter.put("connection", array);
        readerParameter.put("username",dataBaseEntity.getJdbcUser());
        readerParameter.put("password",dataBaseEntity.getJdbcPassword());
        readerParameter.put("column",sourceColumn);
        readerObj.put("parameter",readerParameter);
        parseViewWriterObj(formTaskEntity,thirdPartyToken,targetColumn,formTaskMapperList);
    }



    @Override
    public void start() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("reader",readerObj);
        jsonObject.put("writer",viewWriterObj);
        executeEtl(jsonObject.toJSONString(),"table",null,false);
        this.successCount = 0;
        this.failCount = 0;
        FormTaskLogEntity formTaskLogEntity = new FormTaskLogEntity();
        Boolean flag = true;
        long startTime = System.currentTimeMillis();
        try {
            formTaskLogEntity.setStartTime(new Date());
            formTaskLogService.saveOrUpdate(formTaskLogEntity);
            executeDistributionTableEtl(realTimeDistributeConfig.getRealTimeDistributeTableConfigList());
            executeDistributionApiEtl(realTimeDistributeConfig.getRealTimeDistributeInterfaceConfigList());
        }catch (Exception e){
            flag = false;
            formTaskLogEntity.setError(e.toString());
        }finally {
            if (!flag){
                formTaskLogEntity.setStatus(RunStateEnums.error.getValue());
            }else {
                formTaskLogEntity.setStatus(RunStateEnums.finish.getValue());
            }
            long endTime = System.currentTimeMillis();
            formTaskLogEntity.setEndTime(new Date());
            formTaskLogEntity.setTabConfNum(realTimeDistributeConfig.getRealTimeDistributeTableConfigList().size());
            formTaskLogEntity.setApiConfNum(realTimeDistributeConfig.getRealTimeDistributeInterfaceConfigList().size());
            formTaskLogEntity.setRecords((this.apiFailCount+this.apiSuccessCount)+(this.failCount+this.successCount));
            formTaskLogEntity.setTotalTime(String.valueOf((endTime-startTime)));
            formTaskLogEntity.setJobId(jobInstance.getInstId());
            formTaskLogEntity.setTaskId(jobInstance.getBusId());
            formTaskLogService.saveOrUpdate(formTaskLogEntity);
        }
    }

    private void executeDistributionApiEtl(List<RealTimeDistributeInterfaceConfig> realTimeDistributeInterfaceConfigList) {
        for (RealTimeDistributeInterfaceConfig interfaceConfig : realTimeDistributeInterfaceConfigList) {
            List<FiledMappingTable> filedMappingTableList = interfaceConfig.getFiledMappingTableList();
            List<String> sourceColumn = new ArrayList<>();
            List<String> purposeColumn = new ArrayList<>();
            StringBuffer sourceBuffer = new StringBuffer();
            parseFiledTableList(filedMappingTableList,sourceBuffer,sourceColumn,purposeColumn);
            JSONObject jsonObject = new JSONObject();
            JSONObject readerObj = parseDistributionReaderObj(sourceColumn, sourceBuffer);
            JSONObject writerObj = parseApiWriterObj(interfaceConfig, purposeColumn);
            jsonObject.put("reader",readerObj);
            jsonObject.put("writer",writerObj);
            executeEtl(com.alibaba.fastjson2.JSON.toJSONString(jsonObject),"api",interfaceConfig.getDistributionTitle(),true);
        }
    }

    private JSONObject parseApiWriterObj(RealTimeDistributeInterfaceConfig interfaceConfig, List<String> purposeColumn) {
        JSONObject jsonObject = new JSONObject();
        JSONObject parameterObj = new JSONObject();
        parameterObj.put("column",purposeColumn);
        InterfaceConf apiConf = interfaceService.getInterfaceConfById(interfaceConfig.getBusinessInterfaceId(), null);
        if (apiConf.getType().equals(InterfaceTypeEnums.TypeEnums.httpType.getValue())){
            HttpRequestConf httpRequestConf = new ObjectMapper().convertValue(apiConf.getRequestConf(), HttpRequestConf.class);
            Map<String, String> headerMap = new HashMap<>();
            List<InterfaceHearderConf> headers = httpRequestConf.getHeaders();
            for (InterfaceHearderConf header : headers) {
                if (header.getType().equals(InterfaceTypeEnums.parameterTypeEnums.constantType.getValue())){
                    headerMap.put(header.getCode(),header.getValue());
                }else if (header.getType().equals(InterfaceTypeEnums.parameterTypeEnums.certificationType.getValue())){
                    headerMap.put(header.getCode(),"");
                    parameterObj.put("tokenKey",header.getCode());
                }
            }
            parameterObj.put("header",headerMap);
            List<InterfaceParamConf> param = httpRequestConf.getParam();
            if (param.size()>0){
                Map<String, Object> collect = param.stream().filter(item -> item.getType().equals(InterfaceTypeEnums.parameterTypeEnums.constantType.getValue()))
                        .collect(Collectors.toMap(InterfaceParamConf::getCode, InterfaceParamConf::getValue));
                parameterObj.put("params",collect);
            }

            if (httpRequestConf.getReqModel().equals("1")){
                String interfaceParamType = httpRequestConf.getInterfaceParamType();
                if (interfaceParamType.equals("2")){
                    parameterObj.put("requestBodyType","json");
                }else {
                    parameterObj.put("requestBodyType","form-data");
                }
            }
            parameterObj.put("url",httpRequestConf.getUrl());
            parameterObj.put("method",getRequestMethod(httpRequestConf.getReqModel()));
            if (StringUtil.isNotEmpty(httpRequestConf.getPreAuthenticationId())){
                InterfaceConf preApiConf =  interfaceService.getInterfaceConfById(httpRequestConf.getPreAuthenticationId(),null);
                HttpRequestConf preApiConfRequestConf = (HttpRequestConf) preApiConf.getRequestConf();
                InterfaceRespConf interfaceRespConf = preApiConfRequestConf.getInterfaceRespConf();
                parameterObj.put("valuePath",interfaceRespConf.getDataValuePath());
                parameterObj.put("preAuthMethod",getRequestMethod(preApiConfRequestConf.getReqModel()));
                parameterObj.put("preAuthUrl",preApiConfRequestConf.getUrl());
                if (preApiConfRequestConf.getReqModel().equals("1")){
                    String interfaceParamType = preApiConfRequestConf.getInterfaceParamType();
                    if (interfaceParamType.equals("2")){
                        parameterObj.put("authRequestBodyType","json");
                    }else {
                        parameterObj.put("authRequestBodyType","form-data");
                    }
                }
                Map<String, Object> map = new HashMap<>();
                List<InterfaceBodyConf> bodyConf = preApiConfRequestConf.getBodyConf();
                bodyConf.stream().forEach(item->{
                    if (BeanUtil.isNotEmpty(item.getChildren()) && item.getChildren().size()>0){
                        map.put(item.getCode(),getChlidNodeValue(item.getChildren()));
                    }else {
                        map.put(item.getCode(),item.getValue());
                    }
                });
                Map<String, Object> collect = preApiConfRequestConf.getParam().stream().collect(Collectors.toMap(InterfaceParamConf::getCode, InterfaceParamConf::getValue));
                parameterObj.put("authParams",collect);
                Map<String, String> authHeaderMap = preApiConfRequestConf.getHeaders().stream().collect(Collectors.toMap(InterfaceHearderConf::getCode, InterfaceHearderConf::getValue));
                parameterObj.put("preAuthHeader",authHeaderMap);
            }
        }
        jsonObject.put("parameter",parameterObj);
        jsonObject.put("name","httpwriter");
        return jsonObject;
    }

    private Map<String, Object> getChlidNodeValue(List<InterfaceBodyConf> children) {
        Map<String, Object> childNodeMap = new HashMap<>();
        children.stream().forEach(item->{
            if (BeanUtil.isNotEmpty(item.getChildren()) && item.getChildren().size()>0){
                childNodeMap.put(item.getCode(),getChlidNodeValue(item.getChildren()));
            }else {
                childNodeMap.put(item.getCode(),item.getValue());
            }
        });
        return childNodeMap;
    }

    private void executeDistributionTableEtl(List<RealTimeDistributeTableConfig> realTimeDistributeTableConfigList) {
        for (RealTimeDistributeTableConfig realTimeDistributeTableConfig : realTimeDistributeTableConfigList) {
            List<FiledMappingTable> filedMappingTableList = realTimeDistributeTableConfig.getFiledMappingTableList();
            List<String> sourceColumnName = new ArrayList<>();
            StringBuffer sourceBuffer = new StringBuffer();
            List<String> purposeColumnName = new ArrayList<>();
            parseFiledTableList(filedMappingTableList,sourceBuffer,sourceColumnName,purposeColumnName);
            JSONObject readerObj = parseDistributionReaderObj(sourceColumnName, sourceBuffer);
            JSONObject writerObj = parseDistributionWriterObj(purposeColumnName, realTimeDistributeTableConfig,filedMappingTableList);
            JSONObject distributionObj = new JSONObject();
            distributionObj.put("reader",readerObj);
            distributionObj.put("writer",writerObj);
            executeEtl(com.alibaba.fastjson2.JSON.toJSONString(distributionObj),"table",realTimeDistributeTableConfig.getDistributionTitle(),true);
        }
    }

    private void parseFiledTableList(List<FiledMappingTable> filedMappingTableList, StringBuffer sourceBuffer, List<String> sourceColumnName, List<String> purposeColumnName) {
        for (FiledMappingTable filedMappingTable : filedMappingTableList) {
            if (StringUtil.isNullOrEmpty(sourceBuffer.toString())){
                sourceBuffer.append(filedMappingTable.getSourceTableField());
            }else {
                sourceBuffer.append(",").append(filedMappingTable.getSourceTableField());
            }
            sourceColumnName.add(filedMappingTable.getSourceTableField());
            purposeColumnName.add(filedMappingTable.getPurposeField());
        }
    }


    private String getRequestMethod(String type){
        String value = "get";
        if ("1".equals(type)){
            value = "post";
        }
        return value;
    }


    private void executeEtl(String jsonStr, String type,String distributionName, boolean flag){
        EtlConf etlConf = JSON.parseObject(jsonStr, EtlConf.class);
        MetricRegistry registry = new MetricRegistry();
        String etlInstId = UuidUtil.shortUpperUuid();
        String pluginId = etlInstId + "-" + String.format("%04d", 1);
        ConsoleReporter reporter =null;
        EtlPluginExecutor etlPluginExecutor = new EtlPluginExecutor(etlConf, null, registry, jobInstance.getDefId(), jobInstance.getInstId(), pluginId);
        try {
            etlPluginExecutor.doStart();
            etlPluginExecutor.getAttemptCount();

            reporter = ConsoleReporter.forRegistry(registry).build();
            SortedMap<String, Counter> counters = registry.getCounters();
            reporter.start(20, TimeUnit.SECONDS);

            while (!etlPluginExecutor.isTaskFinished()) {
                try {
                    TimeUnit.NANOSECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Counter failedCount = counters.get(jobInstance.getInstId() + "." + "writeSpeed" + ".writeFailedRecords");
            Counter totalCount = counters.get(jobInstance.getInstId() + "." + "channel" + ".totalRecords");
            if (type.equals("table")){
                this.failCount+=failedCount.getCount();
                this.successCount+=(totalCount.getCount()-failedCount.getCount());
            }else {
                this.apiFailCount+=failedCount.getCount();
                this.apiSuccessCount+=(totalCount.getCount()-failedCount.getCount());
            }
            if (flag){
                saveEtlLog(failedCount,totalCount,counters,jsonStr,distributionName,type);
            }
        }catch (Exception e){

        }finally {
            log.info("==============定义{}ETL任务执行完成==============", etlInstId);
            reporter.report();
            reporter.close();
            etlPluginExecutor.shutdown();
        }
    }

    private void saveEtlLog(Counter failedCount, Counter totalCount, SortedMap<String, Counter> counters,
                            String jsonStr, String distributionName,String distributionType) {
        FormTaskEtlLogEntity formTaskEtlLogEntity = new FormTaskEtlLogEntity();
        formTaskEtlLogEntity.setTaskId(jobInstance.getBusId());
        formTaskEtlLogEntity.setJobId(jobInstance.getInstId());
        String aesStr = AESUtil.aesEncode(jsonStr);
        formTaskEtlLogEntity.setExecuteJson(aesStr);
        formTaskEtlLogEntity.setStatus(SystemConst.NORMAL_STATUS);
        formTaskEtlLogEntity.setFailCount(Integer.valueOf(String.valueOf(failedCount.getCount())));
        formTaskEtlLogEntity.setSuccessCount(Integer.valueOf(String.valueOf(totalCount.getCount()-failedCount.getCount())));
        formTaskEtlLogEntity.setDistributionName(distributionName);
        formTaskEtlLogEntity.setDistributionType(distributionType);
        etlLogService.saveOrUpdate(formTaskEtlLogEntity);
    }

    @Override
    public void destroy() {

    }

    @Override
    public JobHandler clone() {
        try {
            return (JobHandler) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new SchedulerException("调度服务克隆异常！", e);
        }
    }

    private void parseViewWriterObj(FormTaskEntity formTaskEntity, String thirdPartyToken, List<String> targetColumn, List<FormTaskMapperEntity> formTaskMapperList){
        JSONObject writerObj = new JSONObject();
        JSONObject writerParameter = new JSONObject();
        View view = formService.getViewById(formTaskEntity.getViewId());
        this.view  =view;
        DataBaseEntity targetViewDb = dataBaseService.asyncQueryById(view.getDatasourceId(), thirdPartyToken);
        writerObj.put("name",targetViewDb.getDbType()+"writer");


        String idField = view.getIdField();
        String primaryKey = formTaskMapperList.stream().filter(item -> idField.equals(item.getSourceCloumn())).findFirst().get().getTargetCloumn();

        JSONObject writerConnectionObj = new JSONObject();
        JSONArray writerArray = new JSONArray();
        writerConnectionObj.put("table",Arrays.asList(view.getLinkTable()));
        writerArray.add(writerConnectionObj);
        writerParameter.put("primaryKey", Arrays.asList(primaryKey));
        writerParameter.put("connection",writerArray);
        writerParameter.put("column",targetColumn);
        writerParameter.put("username",targetViewDb.getJdbcUser());
        writerParameter.put("password",targetViewDb.getJdbcPassword());
        writerParameter.put("jdbcUrl",targetViewDb.getJdbcUrl());
        writerParameter.put("writeMode",checkDbTypeGetWriteMode(targetViewDb.getDbType()));
        writerObj.put("parameter",writerParameter);
        viewWriterObj = writerObj;
    }


    private JSONObject parseDistributionWriterObj(List<String> purposeColumnName, RealTimeDistributeTableConfig realTimeDistributeTableConfig, List<FiledMappingTable> filedMappingTableList){
        JSONObject writerObj = new JSONObject();
        DataBaseEntity db = realTimeDistributeTableConfig.getDataBaseEntity();
        JSONObject writerParameter = new JSONObject();
        writerObj.put("name",db.getDbType()+"writer");


        JSONObject writerConnectionObj = new JSONObject();
        JSONArray writerArray = new JSONArray();
        writerConnectionObj.put("table",Arrays.asList(realTimeDistributeTableConfig.getTableName()));
        writerArray.add(writerConnectionObj);

        String idField = view.getIdField();
        String primaryKey = filedMappingTableList.stream()
                .filter(item->idField.equals(item.getSourceTableField()) || idField.equals(item.getSourceTableField().toLowerCase()))
                .findFirst().get().getPurposeField();

        writerParameter.put("pkColumn",Arrays.asList(primaryKey));
        writerParameter.put("connection",writerArray);
        writerParameter.put("jdbcUrl",db.getJdbcUrl());
        writerParameter.put("column",purposeColumnName);
        writerParameter.put("username",db.getJdbcUser());
        writerParameter.put("password",db.getJdbcPassword());

        writerParameter.put("writeMode",checkDbTypeGetWriteMode(db.getDbType()));
        writerObj.put("parameter",writerParameter);


        return writerObj;
    }

    private JSONObject parseDistributionReaderObj(List<String> sourceColumnName, StringBuffer sourceBuffer){
        JSONObject tempObj = new JSONObject();
        tempObj = (JSONObject) readerObj.clone();
        Configuration from = Configuration.from(tempObj);
        JSONObject parameter = (JSONObject) from.get("parameter");
        String sql = "select "+sourceBuffer.toString()+ " from  (" + executeSql +") a";
        JSONArray array = new JSONArray();
        JSONObject readerConnectionObj = new JSONObject();
        array.add(readerConnectionObj.put("querySql",sql));
        parameter.put("connection",readerConnectionObj);
        parameter.put("column",sourceColumnName);
        tempObj.put("parameter",parameter);
        return tempObj;
    }

    private String checkDbTypeGetWriteMode(String dbType){
        switch (dbType.toUpperCase()){
            case "MYSQL":
                return "replace";
            default:
                return "merge";
        }
    }


    private void initService() {
        if (realtimeDistributionService==null){
            realtimeDistributionService = (IMdmToolsRealtimeDistributionService) AppUtil.getBean(IMdmToolsRealtimeDistributionService.class);
        }
        if (formTaskService==null){
            formTaskService = (IFormTaskService) AppUtil.getBean(IFormTaskService.class);
        }
        if (formModelService==null){
            formModelService = (IFormModelService) AppUtil.getBean(IFormModelService.class);
        }
        if (formModelParamsService==null){
            formModelParamsService = (IFormModelParamsService) AppUtil.getBean(IFormModelParamsService.class);
        }
        if (formTaskParamsService == null){
            formTaskParamsService = (IFormTaskParamsService) AppUtil.getBean(IFormTaskParamsService.class);
        }
        if (dataBaseService==null){
            dataBaseService = (IUcDataBaseService) AppUtil.getBean(IUcDataBaseService.class);
        }
        if (formTaskMapperService==null){
            formTaskMapperService = (IFormTaskMapperService) AppUtil.getBean(IFormTaskMapperService.class);
        }
        if (formService ==null){
            formService = (FormService) AppUtil.getBean(FormService.class);
        }
        if (formTaskLogService == null){
            formTaskLogService = (IFormTaskLogService) AppUtil.getBean(IFormTaskLogService.class);
        }
        if (environment ==null){
            environment = (Environment) AppUtil.getBean(Environment.class);
        }
        if (interfaceService==null){
            interfaceService = (IInterfaceService) AppUtil.getBean(IInterfaceService.class);
        }
        if (etlLogService==null){
            etlLogService = (IFormTaskEtlLogService) AppUtil.getBean(IFormTaskEtlLogService.class);
        }
    }
}
